<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 7.3.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/favicon.ico">
  <link rel="icon" type="image/png" sizes="32x32" href="/favicon.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/favicon.ico">
  <link rel="mask-icon" href="/favicon.ico" color="#222">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="https://fonts.loli.net/css?family=Lato:300,300italic,400,400italic,700,700italic%7CZCOOL+QingKe+HuangYou:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" integrity="sha256-DfWjNxDkM94fVBWx1H5BMMp0Zq7luBlV8QRcSES7s+0=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.css" integrity="sha256-Vzbj7sDDS/woiFS3uNKo8eIuni59rjyNGtXfstRzStA=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/pace/1.2.4/themes/blue/pace-theme-bounce.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/pace/1.2.4/pace.min.js" integrity="sha256-gqd7YTjg/BtfqWSwsJOvndl0Bxc8gFImLEkXQT8+qj0=" crossorigin="anonymous"></script>

<script class="next-config" data-name="main" type="application/json">{"hostname":"www.kaaaaai.cn","root":"/","images":"/images","scheme":"Gemini","darkmode":false,"version":"8.12.1","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":true,"style":"mac"},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":"valine","storage":true,"lazyload":true,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>

    <meta name="description" content="一、前言　　在维护一个项目时碰见一个问题，调用了一个方法后不起作用，这种问题一般有两个解决思路，一个是看方法有没有起作用，另一个是看是不是其他的方法打断了这个方法，比如设置 UIButton 的隐藏，但在另一个地方，又把它设置成显示了。这种问题在工程里通过调试代码一般都很好解决。　　但是当它发生在我调用了一个 SDK 方法不起作用时，按照上文的思路，一查看是否是 SDK 方法的问题，这个除了向 S">
<meta property="og:type" content="article">
<meta property="og:title" content="iOS - Runtime 学习">
<meta property="og:url" content="https://www.kaaaaai.cn/ios-runtime-study.html">
<meta property="og:site_name" content="壹拾肆">
<meta property="og:description" content="一、前言　　在维护一个项目时碰见一个问题，调用了一个方法后不起作用，这种问题一般有两个解决思路，一个是看方法有没有起作用，另一个是看是不是其他的方法打断了这个方法，比如设置 UIButton 的隐藏，但在另一个地方，又把它设置成显示了。这种问题在工程里通过调试代码一般都很好解决。　　但是当它发生在我调用了一个 SDK 方法不起作用时，按照上文的思路，一查看是否是 SDK 方法的问题，这个除了向 S">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2019-08-16T02:24:52.000Z">
<meta property="article:modified_time" content="2020-11-22T01:32:52.000Z">
<meta property="article:author" content="Kaaaaai">
<meta property="article:tag" content="EXP">
<meta property="article:tag" content="OC">
<meta property="article:tag" content="Xcode">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://www.kaaaaai.cn/ios-runtime-study.html">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"https://www.kaaaaai.cn/ios-runtime-study.html","path":"/ios-runtime-study.html","title":"iOS - Runtime 学习"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>iOS - Runtime 学习 | 壹拾肆</title>
  
    <script async src="https://www.googletagmanager.com/gtag/js?id=UA-102185873-1"></script>
  <script class="next-config" data-name="google_analytics" type="application/json">{"tracking_id":"UA-102185873-1","only_pageview":false}</script>
  <script src="/js/third-party/analytics/google-analytics.js"></script>

  <script src="/js/third-party/analytics/baidu-analytics.js"></script>
  <script async src="https://hm.baidu.com/hm.js?9578d14210d67becef48447e4f6b3f20"></script>



<link rel="dns-prefetch" href="https://waline-server-kaaaaai.vercel.app"> <script type="text/javascript" src="/js/link-highlight.js"></script>

  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
<link rel="alternate" href="/atom.xml" title="壹拾肆" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">壹拾肆</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">有些安排是多余的 这片空旷对我有益</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-moments"><a href="/bb/" rel="section"><i class="fa fa-coffee fa-fw"></i>碎片</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%80%E3%80%81%E5%89%8D%E8%A8%80"><span class="nav-number">1.</span> <span class="nav-text">一、前言</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BA%8C%E3%80%81%E6%A6%82%E5%BF%B5"><span class="nav-number">2.</span> <span class="nav-text">二、概念</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%89%E3%80%81%E5%BA%94%E7%94%A8%E5%9C%BA%E6%99%AF"><span class="nav-number">3.</span> <span class="nav-text">三、应用场景</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1%E3%80%81%E5%85%B3%E8%81%94%E5%AF%B9%E8%B1%A1-Objective-C-Associated-Objects-%E7%BB%99%E5%88%86%E7%B1%BB%E5%A2%9E%E5%8A%A0%E5%B1%9E%E6%80%A7"><span class="nav-number">3.1.</span> <span class="nav-text">1、关联对象(Objective-C Associated Objects)给分类增加属性</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2%E3%80%81%E6%96%B9%E6%B3%95%E4%BA%A4%E6%8D%A2%EF%BC%88%E9%BB%91%E9%AD%94%E6%B3%95%EF%BC%89"><span class="nav-number">3.2.</span> <span class="nav-text">2、方法交换（黑魔法）</span></a></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Kaaaaai"
      src="https://s2.loli.net/2022/03/29/GSJKrCRi4owa9hq.png">
  <p class="site-author-name" itemprop="name">Kaaaaai</p>
  <div class="site-description" itemprop="description">🐨🐨</div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">100</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">7</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">66</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="sidebar-button site-overview-item animated">
    <button><i class="fa fa-comment"></i>
      Chat
    </button>
  </div>
  <div class="links-of-author site-overview-item animated">
      <span class="links-of-author-item">
        <a href="https://github.com/Kaaaaai" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;Kaaaaai" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://stackoverflow.com/users/8342030/kaaaaai" title="StackOverflow → https:&#x2F;&#x2F;stackoverflow.com&#x2F;users&#x2F;8342030&#x2F;kaaaaai" rel="noopener" target="_blank"><i class="fab fa-stack-overflow fa-fw"></i>StackOverflow</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://www.instagram.com/edisonlllllk" title="Instagram → https:&#x2F;&#x2F;www.instagram.com&#x2F;edisonlllllk" rel="noopener" target="_blank"><i class="fab fa-instagram fa-fw"></i>Instagram</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:root@kaaaaai.cn" title="E-Mail → mailto:root@kaaaaai.cn" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>



        </div>
      </div>

      
    <!-- 网易云歌曲 -->
    <iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width=330 height=86 src="//music.163.com/outchain/player?type=2&id=421203025&auto=1&height=66"></iframe>
        <div class="back-to-top animated" role="button" aria-label="返回顶部">
          <i class="fa fa-arrow-up"></i>
          <span>0%</span>
        </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://www.kaaaaai.cn/ios-runtime-study.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="https://s2.loli.net/2022/03/29/GSJKrCRi4owa9hq.png">
      <meta itemprop="name" content="Kaaaaai">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="壹拾肆">
      <meta itemprop="description" content="🐨🐨">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="iOS - Runtime 学习 | 壹拾肆">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          iOS - Runtime 学习
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2019-08-16 10:24:52" itemprop="dateCreated datePublished" datetime="2019-08-16T10:24:52+08:00">2019-08-16</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E7%AC%94%E8%AE%B0/" itemprop="url" rel="index"><span itemprop="name">笔记</span></a>
        </span>
    </span>

  
    <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv">
      <span class="post-meta-item-icon">
        <i class="far fa-eye"></i>
      </span>
      <span class="post-meta-item-text">阅读次数：</span>
      <span id="busuanzi_value_page_pv"></span>
    </span>
  
  <span class="post-meta-item">
    
    <span class="post-meta-item-icon">
      <i class="far fa-comment"></i>
    </span>
    <span class="post-meta-item-text">Waline：</span>
  
    <a title="waline" href="/ios-runtime-study.html#waline" itemprop="discussionUrl">
      <span class="post-comments-count waline-comment-count" data-path="/ios-runtime-study.html" itemprop="commentCount"></span>
    </a>
  </span>
  
  
    <span class="post-meta-break"></span>
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>6.7k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>6 分钟</span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h2 id="一、前言"><a href="#一、前言" class="headerlink" title="一、前言"></a>一、前言</h2><p>　　在维护一个项目时碰见一个问题，调用了一个方法后不起作用，这种问题一般有两个解决思路，一个是看方法有没有起作用，另一个是看是不是其他的方法打断了这个方法，比如设置 UIButton 的隐藏，但在另一个地方，又把它设置成显示了。这种问题在工程里通过调试代码一般都很好解决。<br>　　但是当它发生在我调用了一个 SDK 方法不起作用时，按照上文的思路，一查看是否是 SDK 方法的问题，这个除了向 SDK 提供人员反应没有其他更好的解决方法了，二是查看是否其他地方也调用了这个方法，使用了不同的参数导致本次的调用失效了。如果这个方法调用的少，可以全局搜索，然后注释掉方法，但是如果之前项目不是你开发的，你只是后期切入进来，同时代码结构一时半会还不能很好把握到，总之想快速利落的排除问题，这时你可以考虑用 Runtime 的特性，把 SDK 里的方法用自己写的替换掉。<br>　　先老调重弹一遍，什么是 Runtime？
　　</p>
<h2 id="二、概念"><a href="#二、概念" class="headerlink" title="二、概念"></a>二、概念</h2><p>　　Objective-C是动态语言，它将很多静态语言在编译和链接时做的事放到了运行时，这个运行时系统就是 Runtime。<br>Runtime 其实就是一个库，它基本上是用 C 和汇编写的一套 API，这个库使C语言有了面向对象的能力。<br>静态语言：在编译的时候会决定调用哪个函数。<br>动态语言（OC）：在运行的时候根据函数的名称找到对应的函数来调用。</p>
<p>　　然后还有一些需要了解的基本概念：</p>
<ul>
<li><strong>isa</strong>：OC 中，类和类的实例在本质上没有区别，都是对象，任何对象都有isa 指针，它指向类或元类。</li>
<li><strong>SEL</strong>：SEL（又叫选择器）是方法的 selector 的指针。方法的 selector 表示运行时方法的名字。OC在编译时，会依据每一个方法的名字、参数，生成一个唯一的整型标识(Int类型的地址)，这个标识就是 SEL。</li>
<li><strong>IMP</strong>：IMP 是一个函数指针，指向方法最终实现的首地址。SEL 就是为了查找方法的最终实现IMP。</li>
<li><strong>Method</strong>：用于表示类定义中的方法，它的结构体中包含一个 SEL 和 IMP，相当于在 SEL 和 IMP 之间作了一个映射。</li>
<li><strong>消息机制</strong>：任何方法的调用本质就是发送一个消息。编译器会将消息表达式[receiver message]转化为一个消息函数 objc_msgSend(receiver, selector)。</li>
<li><strong>Runtime 的使用</strong>：获取属性列表，获取成员变量列表，获得方法列表，获取协议列表，方法交换（黑魔法），动态的添加方法，调用私有方法，为分类添加属性。</li>
</ul>
<h2 id="三、应用场景"><a href="#三、应用场景" class="headerlink" title="三、应用场景"></a>三、应用场景</h2><ul>
<li>关联对象(Objective-C Associated Objects)给分类增加属性</li>
<li>方法交换 &#x2F; 黑魔法(Method Swizzling)</li>
<li>实现 NSCoding 的自动归档和自动解档</li>
<li>实现字典和模型的自动转换(MJExtension)</li>
</ul>
<p>　　这里介绍前两种。
　　</p>
<h3 id="1、关联对象-Objective-C-Associated-Objects-给分类增加属性"><a href="#1、关联对象-Objective-C-Associated-Objects-给分类增加属性" class="headerlink" title="1、关联对象(Objective-C Associated Objects)给分类增加属性"></a>1、关联对象(Objective-C Associated Objects)给分类增加属性</h3><p>我们都是知道分类是不能自定义属性和变量的。下面通过关联对象实现给分类添加属性。</p>
<p>关联对象 Runtime提 供了下面几个接口：</p>
<figure class="highlight objectivec"><figcaption><span>Objective-C</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 关联对象</span></span><br><span class="line"><span class="type">void</span> objc_setAssociatedObject(<span class="type">id</span> object, <span class="keyword">const</span> <span class="type">void</span> *key, <span class="type">id</span> value, objc_AssociationPolicy policy)</span><br><span class="line"><span class="comment">// 获取关联的对象</span></span><br><span class="line"><span class="type">id</span> objc_getAssociatedObject(<span class="type">id</span> object, <span class="keyword">const</span> <span class="type">void</span> *key)</span><br><span class="line"><span class="comment">// 移除关联的对象</span></span><br><span class="line"><span class="type">void</span> objc_removeAssociatedObjects(<span class="type">id</span> object)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 参数解释</span></span><br><span class="line"><span class="comment">// id object：被关联的对象</span></span><br><span class="line"><span class="comment">// const void *key：关联的 key，要求唯一</span></span><br><span class="line"><span class="comment">// id value：关联的对象</span></span><br><span class="line"><span class="comment">// objc_AssociationPolicy policy：内存管理的策略</span></span><br></pre></td></tr></table></figure>

<p><strong>例子：</strong></p>
<figure class="highlight objectivec"><figcaption><span>Objective-C</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">///-----------------------</span></span><br><span class="line"><span class="comment">/// NSObject+BRModel.h</span></span><br><span class="line"><span class="comment">///-----------------------</span></span><br><span class="line"><span class="meta">#import <span class="string">&lt;Foundation/Foundation.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">@interface</span> <span class="title">NSObject</span> (<span class="title">BRModel</span>)</span></span><br><span class="line"><span class="comment">/** 1.获取类的属性列表数组 */</span></span><br><span class="line">+ (<span class="built_in">NSArray</span> *)br_objectProperties;</span><br><span class="line"></span><br><span class="line"><span class="comment">/** 2.字典转模型：给定一个字典，返回 self 类对应的模型对象 */</span></span><br><span class="line">+ (<span class="keyword">instancetype</span>)br_objectWithDictionary:(<span class="built_in">NSDictionary</span> *)dict;</span><br><span class="line"></span><br><span class="line"><span class="keyword">@end</span></span><br><span class="line"></span><br><span class="line"><span class="comment">///-----------------------</span></span><br><span class="line"><span class="comment">/// NSObject+BRModel.m</span></span><br><span class="line"><span class="comment">///-----------------------</span></span><br><span class="line"><span class="meta">#import <span class="string">&quot;NSObject+BRModel.h&quot;</span></span></span><br><span class="line"><span class="meta">#import <span class="string">&lt;objc/runtime.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> <span class="type">char</span> *kPropertyListKey = <span class="string">&quot;kPropertyListKey&quot;</span>;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">@implementation</span> <span class="title">NSObject</span> (<span class="title">BRModel</span>)</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/// 所有字典转模型框架的核心算法（这里只是实现简单的字典转模型。扩展：要考虑字典的嵌套）</span></span><br><span class="line"><span class="comment">/// 在字典转模型框架中，如果字典嵌套层次结构非常深，框架由于利用递归实现转换，内存消耗大，执行性能不好！</span></span><br><span class="line"><span class="comment">/// YYModel 因为功能简单（在功能上做了取舍，满足大多数情况下使用），所以速度快！</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 1.动态（通过 Runtime 形式）获取类的属性列表</span></span><br><span class="line">+ (<span class="built_in">NSArray</span> *)br_objectProperties &#123;</span><br><span class="line">    <span class="comment">/// 1.利用“关联对象”获取属性的值，如果有，直接返回！(这里获取对象类似于懒加载，只不过分类里面不能创建属性，用“关联对象”来替代)</span></span><br><span class="line">    <span class="comment">/// 这里使用“关联对象”其目的是提高效率（懒加载思想）！</span></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     *  获取关联对象（相当于属性的 getter 方法）</span></span><br><span class="line"><span class="comment">     *  参数1：对象</span></span><br><span class="line"><span class="comment">     *  参数2：动态添加属性的 key（相当于属性名）</span></span><br><span class="line"><span class="comment">     *  返回值：动态添加的“属性值”</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="built_in">NSArray</span> *pList = objc_getAssociatedObject(<span class="keyword">self</span>, kPropertyListKey);</span><br><span class="line">    <span class="keyword">if</span> (pList != <span class="literal">nil</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> pList;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     *  调用运行时方法，获取类的属性列表</span></span><br><span class="line"><span class="comment">     *  class_copyPropertyList():   获取类的 属性 列表方法</span></span><br><span class="line"><span class="comment">     *  class_copyIvarList():       获取类的 成员变量 列表方法</span></span><br><span class="line"><span class="comment">     *  class_copyMethodList():     获取类的 方法 列表方法</span></span><br><span class="line"><span class="comment">     *  class_copyProtocolList():   获取类的 协议 列表方法</span></span><br><span class="line"><span class="comment">     *  参数1：要获取的类</span></span><br><span class="line"><span class="comment">     *  参数2：类属性的个数指针（&amp;属性个数）</span></span><br><span class="line"><span class="comment">     *  返回值：所有属性的数组</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="type">unsigned</span> <span class="type">int</span> count = <span class="number">0</span>;</span><br><span class="line">    <span class="comment">// 获取属性数组（这里 objc_property_t 接收的是数组，需要带 *）</span></span><br><span class="line">    objc_property_t *properties = class_copyPropertyList([<span class="keyword">self</span> <span class="keyword">class</span>], &amp;count);</span><br><span class="line">    <span class="built_in">NSMutableArray</span> *propertyNameArr = [[<span class="built_in">NSMutableArray</span> alloc]init];</span><br><span class="line">    <span class="comment">// 遍历属性数组</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="type">unsigned</span> <span class="type">int</span> i = <span class="number">0</span>; i &lt; count; i++) &#123;</span><br><span class="line">        <span class="comment">// 1&gt; 获取属性(C 语言中的结构体指针，通常不需要带 *)</span></span><br><span class="line">        objc_property_t property = properties[i];</span><br><span class="line">        <span class="comment">// 2&gt; 从 property 中获取属性的名称（即C语言字符串）</span></span><br><span class="line">        <span class="keyword">const</span> <span class="type">char</span> *cName = property_getName(property);</span><br><span class="line">        <span class="comment">// 将C语言字符串转成 OC 字符串</span></span><br><span class="line">        <span class="built_in">NSString</span> *name = [<span class="built_in">NSString</span> stringWithCString:cName encoding:<span class="built_in">NSUTF8StringEncoding</span>];</span><br><span class="line">        <span class="comment">// 3&gt; 添加 OC 属性名到数组</span></span><br><span class="line">        [propertyNameArr addObject:name];</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 释放数组（C 语言中用到了包含 create/copy/...的方法，都需要释放内存）</span></span><br><span class="line">    free(properties);</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     *  2.利用“关联对象”保存属性的值</span></span><br><span class="line"><span class="comment">     *  参数1：self 对象</span></span><br><span class="line"><span class="comment">     *  参数2：动态添加属性的 key（相当于属性名）</span></span><br><span class="line"><span class="comment">     *  参数3：动态添加属性的值</span></span><br><span class="line"><span class="comment">     *  参数4：对象的引用关系（类似于属性中的 nonatomic,assign/copy/retain）</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    objc_setAssociatedObject(<span class="keyword">self</span>, kPropertyListKey, [propertyNameArr <span class="keyword">copy</span>], OBJC_ASSOCIATION_RETAIN_NONATOMIC);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> [propertyNameArr <span class="keyword">copy</span>];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 2.字典转模型：给定一个字典，返回 self 类对应的模型对象</span></span><br><span class="line">+ (<span class="keyword">instancetype</span>)br_objectWithDictionary:(<span class="built_in">NSDictionary</span> *)dict &#123;</span><br><span class="line">    <span class="type">id</span> object = [[<span class="keyword">self</span> alloc]init];</span><br><span class="line">    <span class="comment">// 获取当前对象的属性列表</span></span><br><span class="line">    <span class="comment">// 优化：使用关联对象 pList 的值保存起来，不用每次都去获取</span></span><br><span class="line">    <span class="built_in">NSArray</span> *pList = [<span class="keyword">self</span> br_objectProperties];</span><br><span class="line">    <span class="comment">// 1&gt; 遍历属性数组</span></span><br><span class="line">    [pList enumerateObjectsUsingBlock:^(<span class="type">id</span>  _Nonnull pName, <span class="built_in">NSUInteger</span> idx, <span class="type">BOOL</span> * _Nonnull stop) &#123;</span><br><span class="line">        <span class="type">id</span> pValue = [dict objectForKey:pName];</span><br><span class="line">        <span class="comment">// 使用 KVC 给对象属性赋值</span></span><br><span class="line">        [object setValue:pValue forKey:pName];</span><br><span class="line">    &#125;];</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">    // 2&gt; 遍历字典</span></span><br><span class="line"><span class="comment">    [dict enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull value, BOOL * _Nonnull stop) &#123;</span></span><br><span class="line"><span class="comment">        if ([pList containsObject:key]) &#123;</span></span><br><span class="line"><span class="comment">            // 使用KVC给对象属性赋值</span></span><br><span class="line"><span class="comment">            [object setValue:value forKey:key];</span></span><br><span class="line"><span class="comment">        &#125;</span></span><br><span class="line"><span class="comment">    &#125;];</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line">    <span class="keyword">return</span> object;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">@end</span></span><br></pre></td></tr></table></figure>

<h3 id="2、方法交换（黑魔法）"><a href="#2、方法交换（黑魔法）" class="headerlink" title="2、方法交换（黑魔法）"></a>2、方法交换（黑魔法）</h3><p>下面就是 runtime 的重头戏了，被称作黑魔法的方法交换 Swizzling。交换方法是在 method_exchangeImplementations 里发生的。</p>
<p>使用 Swizzling 的过程中要注意两个问题：</p>
<p>Swizzling 要在 +load 方法中执行</p>
<p>运行时会自动调用每个类的两个方法，+load 与 +initialize。</p>
<p>+load 会在 main 函数之前调用，并且一定会调用。</p>
<p>+initialize 是在第一次调用类方法或实例方法之前被调用，有可能一直不被调用。</p>
<p>一般使用 Swizzling 是为了影响全局，所以为了方法交换一定成功，Swizzling 要放在 +load 中执行。</p>
<p>Swizzling 要在 dispatch_once 中执行</p>
<p>Swzzling 是为了影响全局，所以只让它执行一次就可以了，所以要放在 dispatch_once 中。</p>
<p>例子：</p>
<figure class="highlight objectivec"><figcaption><span>Objective-C</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">///-----------------------</span></span><br><span class="line"><span class="comment">/// UIImageView+BRAdd.h</span></span><br><span class="line"><span class="comment">///-----------------------</span></span><br><span class="line"><span class="meta">#import <span class="string">&lt;UIKit/UIKit.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">@interface</span> <span class="title">UIImageView</span> (<span class="title">BRAdd</span>)</span></span><br><span class="line">- (<span class="type">void</span>)br_setImage:(<span class="built_in">UIImage</span> *)image;</span><br><span class="line"><span class="keyword">@end</span></span><br><span class="line"></span><br><span class="line"><span class="comment">///-----------------------</span></span><br><span class="line"><span class="comment">/// UIImageView+BRAdd.m</span></span><br><span class="line"><span class="comment">///-----------------------</span></span><br><span class="line"><span class="meta">#import <span class="string">&quot;UIImageView+BRAdd.h&quot;</span></span></span><br><span class="line"><span class="meta">#import <span class="string">&lt;objc/runtime.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">@implementation</span> <span class="title">UIImageView</span> (<span class="title">BRAdd</span>)</span></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> *  load 方法 会在类第一次加载的时候（类被加载到运行时的时候）被调用</span></span><br><span class="line"><span class="comment"> *  调用的时间比较靠前，适合在这个方法里做方法交换</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line">+ (<span class="type">void</span>)load &#123;</span><br><span class="line">    <span class="comment">// 方法交换应该被保证，在程序中只会执行一次</span></span><br><span class="line">    <span class="keyword">static</span> <span class="built_in">dispatch_once_t</span> onceToken;</span><br><span class="line">    <span class="built_in">dispatch_once</span>(&amp;onceToken, ^&#123;</span><br><span class="line">        <span class="comment">// 1.获取 UIImageView 类的实例方法 setImage:</span></span><br><span class="line">        Method originalMethod = class_getInstanceMethod([<span class="keyword">self</span> <span class="keyword">class</span>], <span class="keyword">@selector</span>(setImage:));</span><br><span class="line">        <span class="comment">// 2.获取 UIImageView 类的实例方法 br_setImage: （这个方法本身定义在分类中，所以能获取到）</span></span><br><span class="line">        Method swizzledMethod = class_getInstanceMethod([<span class="keyword">self</span> <span class="keyword">class</span>], <span class="keyword">@selector</span>(br_setImage:));</span><br><span class="line">        <span class="comment">// 3.交换方法 setImage: 和 br_setImage:</span></span><br><span class="line">        method_exchangeImplementations(originalMethod, swizzledMethod);</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 当在其它位置调用 setImage: 方法时，就会自动调用 br_setImage: 方法</span></span><br><span class="line">- (<span class="type">void</span>)br_setImage:(<span class="built_in">UIImage</span> *)image &#123;</span><br><span class="line">    <span class="built_in">NSLog</span>(<span class="string">@&quot;%s&quot;</span>, __FUNCTION__);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 在这里我们可以添加自己想添加的内容...</span></span><br><span class="line">    <span class="comment">// 调整图片大小：生成一张和 imageView 一样大的图片</span></span><br><span class="line">    <span class="built_in">UIImage</span> *newImage = [<span class="keyword">self</span> newImage:image size:<span class="keyword">self</span>.bounds.size];</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 调用系统默认的 setImage:方法</span></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     *  注意：交换了方法（互换身份），这时候调用自己，看起来像是死循环，但是其实自己的实现已经被替换了</span></span><br><span class="line"><span class="comment">     *  调用系统的 setImage:方法时，会执行 br_setImage:方法</span></span><br><span class="line"><span class="comment">     *  调用 br_setImage:方法时，会执行系统的 setImage:方法（要注意区分！）</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    [<span class="keyword">self</span> br_setImage:newImage];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 重新生成指定大小的图片</span></span><br><span class="line">- (<span class="built_in">UIImage</span> *)newImage:(<span class="built_in">UIImage</span> *)image size:(<span class="built_in">CGSize</span>)size &#123;</span><br><span class="line">    <span class="built_in">UIGraphicsBeginImageContextWithOptions</span>(size, <span class="literal">YES</span>, <span class="number">0</span>);</span><br><span class="line">    <span class="comment">// 重新绘制图片</span></span><br><span class="line">    [image drawInRect:<span class="built_in">CGRectMake</span>(<span class="number">0</span>, <span class="number">0</span>, size.width, size.height)];</span><br><span class="line">    <span class="comment">// 取得结果</span></span><br><span class="line">    <span class="built_in">UIImage</span> *newImage = <span class="built_in">UIGraphicsGetImageFromCurrentImageContext</span>();</span><br><span class="line">    <span class="comment">// 关闭上下文</span></span><br><span class="line">    <span class="built_in">UIGraphicsEndImageContext</span>();</span><br><span class="line">    <span class="keyword">return</span> newImage;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">@end</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// 扩展：方法交换还有不少应用场景，比如记录页面被点开的次数：只要在 UIViewController 的分类的 +load 中交换 viewDidAppear 方法，在交换的方法中添加记录代码就可以了。</span></span><br></pre></td></tr></table></figure>
    </div>

    
    
    

    <footer class="post-footer">
          <div class="reward-container">
  <div></div>
  <button>
    请喝咖啡
  </button>
  <div class="post-reward">
      <div>
        <img src="/images/loading-style-3.gif" data-original="https://s2.loli.net/2022/07/02/Gce8a5QAqrZ3X9R.gif" alt="Kaaaaai 微信">
        <span>微信</span>
      </div>

  </div>
</div>

          

<div class="post-copyright">
<ul>
  <li class="post-copyright-author">
      <strong>本文作者： </strong>Kaaaaai
  </li>
  <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="https://www.kaaaaai.cn/ios-runtime-study.html" title="iOS - Runtime 学习">https://www.kaaaaai.cn/ios-runtime-study.html</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

          <div class="post-tags">
              <a href="/tags/EXP/" rel="tag"><i class="fa fa-tag"></i> EXP</a>
              <a href="/tags/OC/" rel="tag"><i class="fa fa-tag"></i> OC</a>
              <a href="/tags/Xcode/" rel="tag"><i class="fa fa-tag"></i> Xcode</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/ios-utf8-to-chinese.html" rel="prev" title="iOS - 如何把 Xcode 打印出来的 UTF-8 格式字符变成汉字？">
                  <i class="fa fa-chevron-left"></i> iOS - 如何把 Xcode 打印出来的 UTF-8 格式字符变成汉字？
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/weekly-summary-190819.html" rel="next" title="每周总结 - 0819">
                  每周总结 - 0819 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






    <div class="comments" id="waline"></div>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2024</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Kaaaaai</span>
</div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
    <span title="站点总字数">234k</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">3:33</span>
  </span>
</div>
<div class="busuanzi-count">
    <span class="post-meta-item" id="busuanzi_container_site_uv">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-item" id="busuanzi_container_site_pv">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>
  <!-- time -->
  <div id="show-time">
    <span id="span_dt_dt"></span>
  </div>
  <script>
      function show_date_time() {
        window.setTimeout("show_date_time()", 1000);
        BirthDay = new Date("6/23/2017 19:37:01");
        today = new Date();
        //总时间
        timeold = (today.getTime() - BirthDay.getTime());
        sectimeold = timeold / 1000
        secondsold = Math.floor(sectimeold);
        msPerDay = 24 * 60 * 60 * 1000
        e_daysold = timeold / msPerDay
        daysold = Math.floor(e_daysold);
        e_hrsold = (e_daysold - daysold) * 24;
        hrsold = Math.floor(e_hrsold);
        e_minsold = (e_hrsold - hrsold) * 60;
        minsold = Math.floor((e_hrsold - hrsold) * 60);
        seconds = Math.floor((e_minsold - minsold) * 60);
        span_dt_dt.innerHTML = "已存活 " + daysold + " 天 " + hrsold + " 小时 " + minsold + " 分 " + seconds + " 秒";
    }
    show_date_time();
  </script>

    </div>
  </footer>

  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/next-theme-pjax/0.5.0/pjax.min.js" integrity="sha256-3NkoLDrmHLTYj7csHIZSr0MHAFTXth7Ua/DDt4MRUAg=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.js" integrity="sha256-yt2kYMy0w8AbtF89WXb2P1rfjcP/HTHLT7097U8Y5b8=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/lozad.js/1.16.0/lozad.min.js" integrity="sha256-mOFREFhqmHeQbXpK2lp4nA3qooVgACfh88fpJftLBbc=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script><script src="/js/pjax.js"></script>

  
<script src="https://cdnjs.cloudflare.com/ajax/libs/hexo-generator-searchdb/1.4.0/search.js" integrity="sha256-vXZMYLEqsROAXkEw93GGIvaB2ab+QW6w3+1ahD9nXXA=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>
<script class="next-config" data-name="chatra" type="application/json">{"enable":true,"async":true,"id":"QXLRxXcsfrRJR2KTG"}</script>
<script src="/js/third-party/chat/chatra.js"></script>
<script async src="https://call.chatra.io/chatra.js"></script>



  <script src="/js/third-party/fancybox.js"></script>

  <script src="/js/third-party/pace.js"></script>

  
  <script data-pjax async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>




<script class="next-config" data-name="waline" type="application/json">{"lang":"zh-cn","enable":true,"serverURL":"https://waline-server-kaaaaai.vercel.app","cssUrl":"https://unpkg.com/@waline/client@v2/dist/waline.css","commentCount":true,"pageview":false,"placeholder":"请文明评论呀","avatar":"mm","meta":["nick","mail","link"],"pageSize":10,"visitor":false,"comment_count":true,"requiredFields":[],"libUrl":"//unpkg.com/@waline/client@v2/dist/waline.js","el":"#waline","comment":true,"path":"/ios-runtime-study.html"}</script>
<link rel="stylesheet" href="https://unpkg.com/@waline/client@v2/dist/waline.css">
<script>
document.addEventListener('page:loaded', () => {
  NexT.utils.loadComments(CONFIG.waline.el).then(() =>
    NexT.utils.getScript(CONFIG.waline.libUrl, { condition: window.Waline })
  ).then(() => 
    Waline.init(Object.assign({}, CONFIG.waline,{ el: document.querySelector(CONFIG.waline.el) }))
  );
});
</script>


        <style>
            [bg-lazy] {
                background-image: none !important;
                background-color: #eee !important;
            }
        </style>
        <script>
            window.imageLazyLoadSetting = {
                isSPA: true,
                preloadRatio: 1,
                processImages: null,
            };
        </script><script>window.addEventListener("load",function(){var t=/\.(gif|jpg|jpeg|tiff|png)$/i,r=/^data:image\/[a-z]+;base64,/;Array.prototype.slice.call(document.querySelectorAll("img[data-original]")).forEach(function(a){var e=a.parentNode;"A"===e.tagName&&(e.href.match(t)||e.href.match(r))&&(e.href=a.dataset.original)})});</script><script>!function(r){r.imageLazyLoadSetting.processImages=t;var a=r.imageLazyLoadSetting.isSPA,n=r.imageLazyLoadSetting.preloadRatio||1,d=o();function o(){var t=Array.prototype.slice.call(document.querySelectorAll("img[data-original]")),e=Array.prototype.slice.call(document.querySelectorAll("[bg-lazy]"));return t.concat(e)}function t(t){(a||t)&&(d=o());for(var e,i=0;i<d.length;i++)0<=(e=(e=d[i]).getBoundingClientRect()).bottom&&0<=e.left&&e.top<=(r.innerHeight*n||document.documentElement.clientHeight*n)&&function(){var t,e,a,n,o=d[i];e=function(){d=d.filter(function(t){return o!==t}),r.imageLazyLoadSetting.onImageLoaded&&r.imageLazyLoadSetting.onImageLoaded(o)},(t=o).dataset.loaded||(t.hasAttribute("bg-lazy")?(t.removeAttribute("bg-lazy"),e&&e()):(a=new Image,n=t.getAttribute("data-original"),a.onload=function(){t.src=n,t.removeAttribute("data-original"),t.setAttribute("data-loaded",!0),e&&e()},a.onerror=function(){t.removeAttribute("data-original"),t.setAttribute("data-loaded",!1),t.src=n},t.src!==n&&(a.src=n)))}()}function e(){clearTimeout(t.tId),t.tId=setTimeout(t,500)}t(),document.addEventListener("scroll",e),r.addEventListener("resize",e),r.addEventListener("orientationchange",e)}(this);</script></body>
</html>
